<template>
    <div>
        <NavTopBar title="账号管理" />
        <div class="info">
            <div class="input-item">
                <van-field v-model="state.nickName" label="昵称" />
                <van-field v-model="state.introduceSign" label="个性签名" />
                <van-field
                    v-model="state.password"
                    type="password"
                    label="修改密码"
                />
            </div>
            <van-button
                round
                class="save-btn"
                color="#1baeae"
                type="primary"
                @click="save"
                block
                >保存</van-button
            >
            <van-button
                round
                class="save-btn"
                color="#1baeae"
                type="primary"
                @click="handleLogout"
                block
                >退出登录</van-button
            >
        </div>
    </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, toRefs } from "vue";
import NavTopBar from "@/components/NavTopbar.vue";
import { logout, userInfo, editUserInfo } from "@/apis/user";
import { useStore } from "vuex";
import { removeToken } from "@/utils/auth";
import md5 from "js-md5";
import { Toast } from "vant";
interface UserInfoType {
    introduceSign: string;
    loginName: number | string;
    [propName: string]: any;
}
export default defineComponent({
    components: { NavTopBar },
    setup() {
        let state = reactive<UserInfoType>({
            introduceSign: "",
            loginName: "",
            nickName: "",
        });
        const store = useStore();
        const handleLogout = async () => {
            await logout();
            store.commit("user/setToken", "");
            removeToken();
            window.location.href = "/";
        };

        const save = async () => {
            const params: any = {
                introduceSign: state.introduceSign,
                nickName: state.nickName,
            };
            if (state.password) {
                params.passwordMd5 = md5(state.password);
            }
            await editUserInfo(params);
            Toast.success("保存成功");
        };

        onMounted(async () => {
            const { data } = await userInfo();
            state.nickName = data.nickName;
            state.loginName = data.loginName;
            state.introduceSign = data.introduceSign;
        });
        return { handleLogout, state, save };
    },
});
</script>

<style lang="scss" scoped>
.info {
    padding: 10px;
}
.save-btn {
    width: 80%;
    margin: 20px auto;
}
</style>
